/**
 * @author Hemant
 * This is a public class.It generates a text file with html tag objects and 
 * its properties from tag objects registered in Master.     
 */

/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  Registration;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Hashtable;
import utility.Input;
import file.FileUtility;
//import file.SearchRecord;
import database.RecordSearch;
import dbmanager.*;

public class GenerateTextFile 
{
    private GetIdName get;
    RandomAccessFile rafNew;
    static boolean flag = false;
   // Sort sort;
    String level = "",path,ReportId;
    int counter = 0;
    /**
     * Conctructor accepts tag object name and path for new file to be generated.
     * @param ReportId It is the mastername of registered report.
     * @param db DBManager object
     */
    public GenerateTextFile(String ReportId) 
    {
    	try
    	{    		   			        
	        //Create Sort object
	   //     sort = new Sort(db);
	        //Create GetIdName object
	        get = new GetIdName();
	        //Get master id for Report
	        this.ReportId = ReportId;
	        System.out.println("ReportId :"+ReportId);     
	        path = Input.WEB_REPORTS_FILES+get.getItem(ReportId)+Input.FILRFORMAT;
	        //this.generateFile(ReportNameId);	     
	        
    	}
    	catch (Exception e) 
    	{
                e.printStackTrace();
        }
    }
    /**
     * This method accepts master id for the tag object i.e. ReportName 
     * and writes Text file with tag objects and its properties.
     * @return Returns true if file created.
     */
    public boolean generateFile()
    {
    	boolean filecreated = false;
    	//System.out.println("I'm in generateFile() ");
    	System.out.println("The path is "+path);
        File newfile = new File(path);
        
        if(!newfile.exists())
        {
        	try 
        	{
				if(newfile.createNewFile())
					filecreated = true;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        else
        {
        	System.out.println("File alreday exists");
        	newfile.delete();
        	
        	if(!newfile.exists())
	        {
	        	try {
					if(newfile.createNewFile())
						filecreated = true;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }
        	else
        	{
        		System.out.println("File cannot be deleted");
        	}
        }
        
        // Create random access file object for ReportName path
        try {
			rafNew = new RandomAccessFile(newfile,"rw");
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
    	
    	try
        {            
            String[] records = this.serachForChildProperty(ReportId);
            
            if(records.length!= 0)
            {
                 writeToFile(ReportId,records);      
                 rafNew.close();
            }
            else
            {
                System.out.println("The master has no properties");
            }
        	           
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
       return filecreated;
    }    
    
    /**
     * This method searches for a child property for specifies master id
     * using reports.
     * @param mid Its the master id for which properties are to be searched.
     * @return It returns a String array containg proprties of mid.
     */
   public String [] serachForChildProperty(String mid)
   {
    	String path = Input.MASTERREPORTSPATH+mid+"//"+mid+"_mid"+Input.FILRFORMAT;
    	System.out.println(path);
    	File newreportFile = new File(path);
    	String [] recordset = null;
    	try
        {
            if(newreportFile.exists())
            {
                //SearchRecord search = new SearchRecord(path);
	            
                Hashtable<Object,Object>  midHash = new Hashtable<Object,Object>();
                midHash.put("mid",mid);
                RecordSearch ps = new RecordSearch();
            	ps.setConditionMap(midHash);
            	recordset  = ps.getArrayFromResultSet();
                //recordset  = search.getRecordSet(midHash);
                //recordset = sort.SortOnReference(recordset);
            }
            else
            {
                System.out.println("The file "+path+" does not exists");
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }

        return recordset;
    }
    /**
     * This method writes objects and its properties to text file
     * @param mid Master id of parent object
     * @param recordset Property list of parent object
     */
    public void writeToFile(String mid,String [] recordset)
    {
    	int i = 0;    		  	
        
        try 
		{        	
        	//create path for mid file to be accessed
        	String path = Input.MASTERREPORTSPATH+mid+"//"+mid+"_mid"+Input.FILRFORMAT;
            System.out.println("path :"+path);
            
	        // Create  raf file with thw path
	        RandomAccessFile raf = new RandomAccessFile(path, "rw");
	        
	        //Create FileUtility object for getting coloumn indices of various properties
	        FileUtility fu = new FileUtility(raf);
	        
	        // Get coloumn indices
	        int midIndex = fu.getColumnIndex("mid")-1;
	        int pidIndex = fu.getColumnIndex("pid")-1;
	        int pvIndex = fu.getColumnIndex("pv")-1;
	        int vtIndex = fu.getColumnIndex("vt")-1;
	        int refIndex = fu.getColumnIndex("ref")-1;
            
	        if(counter == 0)
    		{
    			String Temp = get.getItem(mid)+"\n";    			
				rafNew.writeBytes(Temp);
				counter++;
    		}
	        
	    	while(i < recordset.length)
	    	{
	    		String record_elements[] = recordset[i].split("\t");
	            
	            String midVal = record_elements[midIndex];
	            System.out.println("The midval is :"+midVal);
	            String pidVal = record_elements[pidIndex];
	            System.out.println("The pidval is :"+pidVal);
	            String pvVal  = record_elements[pvIndex];
	            System.out.println("The pvVal is :"+pvVal);
	            String vtVal  = record_elements[vtIndex];
	            System.out.println("The vtVal is :"+vtVal);
	            String refVal = record_elements[refIndex];
	            System.out.println("refVal :"+refVal);   		
	            
	    		StringBuffer sbrTemp = new StringBuffer();
	    		String property = get.getItem(pidVal);
	    		//sbrTemp.append(property+Input.ch);
                                
	    		/*if(property.toLowerCase().equals("type"))
	    		{
	    			String temppath = MASTERREPORTSPATH+pvVal+"//"+pvVal+"_mid"+FILRFORMAT;
	    			
	    			//Create  raf file with thw path
	    	        RandomAccessFile tempraf = new RandomAccessFile(temppath,"rw");
	    	        
	    	        //Create FileUtility object for getting coloumn indices of various properties
	    	        FileUtility temp_fu = new FileUtility(tempraf);
	    	        
	    	        // Get coloumn indices	    	        
	    	        int temp_pidIndex = temp_fu.getColumnIndex("pid")-1;
	    	        int temp_pvIndex = temp_fu.getColumnIndex("pv")-1;
	    	        
	    	        String templine = tempraf.readLine();
	    	        while((templine=tempraf.readLine())!= null)
	    	        {
	    	        	String temparr[] = templine.split(String.valueOf(ch));
	    	        	//if(get.getItem(temparr[temp_pidIndex]).toLowerCase().equals("type"))
	    	        	{
	    	        		//if(get.getItem(temparr[temp_pvIndex]).toLowerCase().equals("tag"))
	    	        		{
	    	        			sbrTemp.append(property+Input.ch);
	    	        			
	    	        			if(Integer.parseInt(pvVal)!= 0)
	    	                    {
	    	                        sbrTemp.append(get.getItem(pvVal)+Input.ch);   	                        
	    	                    }
	    	                    else
	    	                    {
	    	                        if(vtVal.toLowerCase().equals("no$"))
	    	                        {
    	                                sbrTemp.append(""+Input.ch);
	    	                        }
	    	                        else
	    	                        {
    	                                sbrTemp.append(vtVal+Input.ch);
	    	                        }
	    	                	}
	    	        			
	    	                    if(refVal.equals("no$") || Integer.parseInt(refVal) == 0)
	    	                    {
	    	                    	sbrTemp.append(refVal+"\n");
	    	                    }
	    	                    else
	    	                    {
	    	                        sbrTemp.append(get.getItem(refVal)+"\n");
	    	                    }
	    	        		
	    	    	    		System.out.println("The line to write is "+sbrTemp.toString());    	
	    	    	    		
	    	    	    		synchronized (this) 
	    	    	    		{
	    	    	    			incrementLevel();
	    	    	    			rafNew.writeBytes(level+sbrTemp.toString());	    
	    	    	    			decrementLevel();
	    	    				}
	    	        		}
	    	        	}
	    	        } 		
		    		i++;
	    		} 	    	
	    		else if(property.toLowerCase().equals("report"))
	    		{
	    			sbrTemp.append(property+Input.ch);
	    			sbrTemp.append(get.getItem(pvVal)+Input.ch);
	    			
	    			if(refVal.equals("no$") || Integer.parseInt(refVal) == 0)
                    {
                    	sbrTemp.append(refVal+"\n");
                    }
                    else
                    {
                        sbrTemp.append(get.getItem(refVal)+"\n");
                    }
	    			
	    			System.out.println("The line to write is "+sbrTemp.toString());    	
    	    		
    	    		synchronized (this) 
    	    		{
    	    			incrementLevel();
    	    			rafNew.writeBytes(level+sbrTemp.toString());	    
    	    			decrementLevel();
    				}
    	    		i++;
	    		}
	    		else
	    		{*/
	    			sbrTemp.append(property+Input.SEPARATOR);
	    			if(Integer.parseInt(pvVal)!= 0)
	                {
	                    sbrTemp.append(get.getItem(pvVal)+Input.SEPARATOR);
	                    flag = true;	
	                }
	                else
	                {
	                    if(vtVal.toLowerCase().equals("no$"))
	                    {
	                            sbrTemp.append(""+Input.SEPARATOR);
	                    }
	                    else
	                    {
	                            sbrTemp.append(vtVal+Input.SEPARATOR);
	                    }
	            	}
	    			
	                try {
						if(refVal.equals("no$") || Integer.parseInt(refVal) == 0)
						{
							sbrTemp.append(refVal+"\n");
						}
						else
						{
						    sbrTemp.append(get.getItem(refVal)+"\n");
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	    		
		    		System.out.println("The line to write is "+sbrTemp.toString());    	
		    		
		    		synchronized (this) 
		    		{
		    			incrementLevel();
		    			rafNew.writeBytes(level+sbrTemp.toString());	    
		    			decrementLevel();
					}
	    		
		    		if(flag == true && !property.toLowerCase().equals("type"))
		    		{
			    		String [] v = this.serachForChildProperty(pvVal);
			    		
			    		if(v != null)
			    		{
			    			incrementLevel();
			    			writeToFile(pvVal,v);
			    			decrementLevel();
			    		}
		    		}
		    		i++;	    			    		
	    		}
	    	//}
    	}
		catch (Exception e) 
		{
			e.printStackTrace();
		}    	
    }
       
    /**
     * This method increments level of object hierarchy
     * @return Incremented level 
     */
    public String incrementLevel()
    {
    	level = level +String.valueOf(Input.SEPARATOR); 
    	return level;
    }
    
    /**
     * This method decrements level of object hierarchy
     * @return Decremented level 
     */
    public void decrementLevel()
    {
    	String temp = "";
    	System.out.println(level);
    	
    	if(level.length() == 0)
    	{
    		System.out.println(level+"     is zero");
		}
    	else
    	{
	    	for(int x = 0;x < level.length();x++)
	    	{
	    		if(level.charAt(x) == '\t' && x>0)
	    		{
	    			temp = temp + '\t';
	    		}
	    	}
    	}
    	level = temp;
    	
    }
    
    public static void main(String args[])
    {
    	DBManager db = new DBManager();
    	GetIdName gin = new GetIdName();
    	String ObjectName = "PO";
    	ObjectName = gin.getId(ObjectName);
        GenerateTextFile gen = new GenerateTextFile(ObjectName);
        gen.generateFile();
    /*    new GenerateTextFile("NewRetailer");
        new GenerateTextFile("NewItem");
        new GenerateTextFile("NewSupplier");
        new GenerateTextFile("NewUser");
        //new GenerateTextFile("MyForm");
        //new GenerateTextFile("master");
         * */
    }
    
}
